import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import { authCenterApi } from '@/api/authCenter'
import { encrypt } from '@/utils/common'
import { ElMessage } from 'element-plus'
import TokenManager from '@/utils/tokenManager'
import { useUserProfile } from '@/composables/useUserProfile'

export function useSSO() {
  const router = useRouter()
  const route = useRoute()
  const userStore = useUserStore()
  const { fetchUserProfile } = useUserProfile()

  const loading = ref(false)

  // SSO redirect URL from query parameters
  const redirectUrl = computed(() => {
    const url = route.query.redirect as string
    if (url) {
      // 支持相对路径和绝对URL
      return url
    }
    return null
  })

  // Redirect after successful authentication
  const handleSuccessRedirect = () => {
    if (redirectUrl.value) {
      // 判断是绝对URL还是相对路径
      try {
        new URL(redirectUrl.value)
        // 是完整的URL，跨域重定向
        window.location.href = redirectUrl.value
      } catch {
        // 是相对路径，使用路由跳转
        router.replace(redirectUrl.value)
      }
    } else {
      // Default redirect to home
      router.replace('/')
    }
  }

  // Login handler
  const handleLogin = async (username: string, password: string) => {
    loading.value = true
    try {
      const res = await authCenterApi.login({
        username,
        password: encrypt(password)
      })
      
      // Handle nested response format
      const responseData = res.data?.data || res.data || res
      
      if ((res.code === 200 || responseData.code === 200) && responseData.accessToken) {
        const { accessToken, refreshToken } = responseData
        
        // Save tokens
        TokenManager.setTokens(accessToken, refreshToken)
        userStore.setToken(accessToken)
        
        ElMessage.success('登录成功!')
        
        // 如果有重定向参数，立即跳转，不等待用户信息加载
        // 目标页面会自动加载用户信息
        if (redirectUrl.value) {
          handleSuccessRedirect()
          return { success: true }
        }
        
        // 没有重定向参数时，先加载用户信息再跳转到首页
        try {
          await fetchUserProfile()
        } catch (profileError) {
          console.warn('Failed to fetch user profile:', profileError)
        }
        
        handleSuccessRedirect()
        
        return { success: true }
      } else {
        const message = res.message || responseData.message || '登录失败，请检查用户名和密码'
        ElMessage.error(message)
        return { success: false, message }
      }
    } catch (error: any) {
      console.error('[SSO Login] Login error:', error)
      
      let message = '登录失败，请稍后再试'
      
      if (error.response?.data) {
        message = error.response.data.message || '登录失败，服务器错误'
      } else if (error.request) {
        message = '登录失败，无法连接到服务器'
      }
      
      ElMessage.error(message)
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // Register handler
  const handleRegister = async (username: string, password: string, email?: string) => {
    loading.value = true
    try {
      const registerData = {
        username,
        password: encrypt(password),
        email: email || undefined
      }
      
      const res = await authCenterApi.register(registerData)
      
      if (res.code === 200 && res.data) {
        ElMessage.success('注册成功！请使用新账号登录')
        return { success: true, username }
      } else {
        const message = res.message || '注册失败，请重试'
        ElMessage.error(message)
        return { success: false, message }
      }
    } catch (error: any) {
      console.error('[SSO Register] Registration error:', error)
      
      let message = '注册失败，请稍后再试'
      
      if (error.response?.data) {
        message = error.response.data.message || '注册失败，服务器错误'
      } else if (error.request) {
        message = '注册失败，无法连接到服务器'
      }
      
      ElMessage.error(message)
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // Check if already logged in
  const checkExistingLogin = () => {
    const token = TokenManager.getAuthToken()
    
    // 如果有 token（无论是否有完整用户信息）
    if (token) {
      // 如果有重定向参数，立即跳转回去（SSO场景）
      if (redirectUrl.value) {
        console.log('[SSO] 检测到已登录且有重定向参数，立即跳转:', redirectUrl.value)
        handleSuccessRedirect()
        return true
      }
      
      // 如果已经有完整的用户信息，跳转到首页
      if (userStore.isLoggedIn) {
        console.log('[SSO] 检测到已登录，跳转到首页')
        handleSuccessRedirect()
        return true
      }
    }
    
    return false
  }

  return {
    loading,
    redirectUrl,
    handleLogin,
    handleRegister,
    handleSuccessRedirect,
    checkExistingLogin
  }
}
